package com.xoa.service.hr;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.hr.HrStaffIncentiveMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.HrCode;
import com.xoa.model.common.HrCodeExample;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.hr.HrStaffIncentive;
import com.xoa.model.hr.HrStaffIncentiveWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 张丽军 on 2018/6/28.
 */
@Service
public class HrStaffIncentiveService {

    private static final String HR_ITEM="HR_STAFF_INCENTIVE1";
    private static final String HR_VALUE="INCENTIVE_TYPE";

    @Resource
    HrStaffIncentiveMapper hrStaffIncentiveMapper;
    @Resource
    UsersMapper usersMapper;
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    HrCodeMapper hrCodeMapper;

    public ToJson<HrStaffIncentive> addHrIncentive(HttpServletRequest request,HrStaffIncentiveWithBLOBs hrStaffIncentiveWithBLOBs) {
        ToJson<HrStaffIncentive> toJson = new ToJson<HrStaffIncentive>();
        //从session中获取当前登录人的信息
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        try{
            int a =0;
            hrStaffIncentiveWithBLOBs.setCreateUserId(users.getUserName());
            hrStaffIncentiveWithBLOBs.setCreateDeptId(users.getDeptId());
            hrStaffIncentiveWithBLOBs.setAddTime(new Date());
            hrStaffIncentiveWithBLOBs.setLastUpdateTime(new Date());
            if(hrStaffIncentiveWithBLOBs.getStaffName()!=null){
                String[] str=hrStaffIncentiveWithBLOBs.getStaffName().split(",");
                for(int i=0;i<str.length;i++){
                    //Users users1 = usersMapper.getUsersByuserId(str[i]);
                    hrStaffIncentiveWithBLOBs.setStaffName(str[i]);
                     a = hrStaffIncentiveMapper.insertSelective(hrStaffIncentiveWithBLOBs);
                }
            }
            if(a>0){
                toJson.setFlag(0);
                toJson.setMsg("新增成功");
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    public ToJson<HrStaffIncentive> updateHrIncentive(HttpServletRequest request, HrStaffIncentiveWithBLOBs hrStaffIncentiveWithBLOBs) {
        ToJson<HrStaffIncentive> toJson = new ToJson<HrStaffIncentive>();
        try{
            int a = 0;
            if(hrStaffIncentiveWithBLOBs.getStaffName()!=null){
                String[] str=hrStaffIncentiveWithBLOBs.getStaffName().split(",");
                for(int i=0;i<str.length;i++){
                    //Users users1 = usersMapper.getUsersByuserId(str[i]);
                    hrStaffIncentiveWithBLOBs.setStaffName(str[i]);
                    a = hrStaffIncentiveMapper.updateByPrimaryKeySelective(hrStaffIncentiveWithBLOBs);
                }
                if(a>0){
                    toJson.setFlag(0);
                    toJson.setMsg("修改成功");
                }
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    public ToJson<HrStaffIncentive> selectById(HttpServletRequest request, Integer incentiveId) {
        ToJson<HrStaffIncentive> toJson = new ToJson<HrStaffIncentive>();
        try{
            HrStaffIncentive hrStaffIncentive = hrStaffIncentiveMapper.selectByPrimaryKey(incentiveId);
           //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(hrStaffIncentive.getAttachmentName()!=null&&!"".equals(hrStaffIncentive.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(hrStaffIncentive.getAttachmentName(),hrStaffIncentive.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.INCENTIVE);
            }
            hrStaffIncentive.setAttachmentList(attachmentList);

            if(hrStaffIncentive!=null){
                toJson.setObject(hrStaffIncentive);
                toJson.setFlag(0);
                toJson.setMsg("详情查询成功");
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    public ToJson<HrStaffIncentive> deleteById(HttpServletRequest request, String incentiveId) {
        ToJson<HrStaffIncentive> toJson = new ToJson<HrStaffIncentive>();
        try{
            int a = 0;
            if(incentiveId!=null){
                String[] str=incentiveId.split(",");
                for(int i=0;i<str.length;i++){
                    int str1 =Integer.valueOf(str[i]);
                    a = hrStaffIncentiveMapper.deleteByPrimaryKey(str1);
                }
            }
            if(a>0){
                toJson.setFlag(0);
                toJson.setMsg("删除成功");
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    public ToJson<HrStaffIncentive> selectList(HttpServletRequest request, HttpServletResponse response, String staffName, String beginDate, String endTime, String incentiveItem, String incentiveType, Integer page, Integer pageSize, boolean useFlag, String export) {
        ToJson<HrStaffIncentive> toJson = new ToJson<HrStaffIncentive>();
        try{
            if(export==null){
                export="0";
            }
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            HashMap<String,Object> map = new HashMap();
            map.put("beginDate",beginDate);
            map.put("endTime",endTime);
            map.put("incentiveItem",incentiveItem);
            map.put("incentiveType",incentiveType);
            map.put("pageParams", pageParams);
            List<HrStaffIncentive> list = null;
            if((staffName!=null&&staffName!="")||(beginDate!=null&&beginDate!="")||(endTime!=null&&endTime!="")||(incentiveItem!=null&&incentiveItem!="")||(incentiveType!=null&&incentiveType!="")){
                if(staffName!=null){
                    if(!StringUtils.checkNull(staffName.toString())){
                        String fromIds = staffName.toString();
                        String[] substring = fromIds.split(",");
                        map.put("staffName",substring);
                    }
                }
            }
            list = hrStaffIncentiveMapper.selectList(map);
            toJson.setTotleNum(hrStaffIncentiveMapper.selectCount());
            toJson.setObj(list);
            toJson.setMsg("列表查询成功");
            toJson.setFlag(0);
            if(export.equals("1")) {
                HSSFWorkbook workbooks = new HSSFWorkbook();
                //HSSFCellStyle styleTitle = createStyle(workbook, (short)16);
                HSSFCellStyle style = workbooks.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                // 创建一个字体样式
                HSSFFont font = workbooks.createFont();
                font.setFontHeightInPoints((short)16);
                font.setBold(true);
                style.setFont(font);
                HSSFSheet sheet = workbooks.createSheet("学习经历信息导出");
                sheet.setDefaultColumnWidth(25);
                sheet.setDefaultRowHeightInPoints(25);
                CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 13);
                sheet.addMergedRegion(cellRangeAddress);
                HSSFRow rowTitle = sheet.createRow(0);
                HSSFCell cellTitle = rowTitle.createCell(0);
                // 为标题设置背景颜色
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                cellTitle.setCellValue("奖惩信息导出");
                cellTitle.setCellStyle(style);
                String[] secondTitles = {"单位员工", "奖惩项目", "奖惩日期", "奖惩属性", "奖惩金额.", "工资月份", "奖惩说明", "登记时间", "备注"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbooks, secondTitles);
                int i = 1;
                for (HrStaffIncentive list1 : list) {
                    if(list1.getIncentiveTime()!=null){
                        list1.setDate(DateFormat.getDatestr(list1.getIncentiveTime()));
                    }
                    if(list1.getAddTime()!=null){
                        list1.setAddTime1((DateFormat.getDatestrTime(list1.getAddTime())));
                    }
                    if(list1.getIncentiveItem()!=null){
                        if(list1.getIncentiveItem().equals("1")){
                            list1.setIncentiveItem1("积极参加工作");
                        }else if(list1.getIncentiveItem().equals("2")){
                            list1.setIncentiveItem1("不迟到不早退");
                        }else if(list1.getIncentiveItem().equals("3")){
                            list1.setIncentiveItem1("违规操作");
                        }else if(list1.getIncentiveItem().equals("4")){
                            list1.setIncentiveItem1("经常迟到早退");
                        }else if(list1.getIncentiveItem().equals("")){
                            list1.setIncentiveItem1("");
                        }
                    }
                    if(list1.getIncentiveType()!=null){
                        if(list1.getIncentiveType().equals("REWARD")){
                            list1.setIncentiveType1("奖励");
                        }else if(list1.getIncentiveType().equals("PUNISHMENT")){
                            list1.setIncentiveType1("惩罚");
                        }else if(list1.getIncentiveType().equals("")){
                            list1.setIncentiveType1("");
                        }
                    }
                    list1.setId(i);


                    i++;
                }
                String[] beanProperty = {"userName", "incentiveItem1", "date", "incentiveType1", "incentiveAmount", "salaryMonth", "incentiveDescription","addTime1","remark"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
                ServletOutputStream out = response.getOutputStream();
                String filename = "奖惩信息导出.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    public ToJson<HrStaffIncentive> importIncentiveInfo(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        ToJson<HrStaffIncentive> json = new ToJson<HrStaffIncentive>(1,"error");
        InputStream in=null;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
                 StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
            int success=0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrStaffIncentiveWithBLOBs hrStaffIncentive = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        hrStaffIncentive = new HrStaffIncentiveWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {

                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            // 用户名
                                            cell.setCellType(CellType.STRING);
                                            String stringCellValue = cell.getStringCellValue();
                                            Users users = usersMapper.getUserByUserName(stringCellValue);
                                            if (users!=null){
                                                Department department = departmentMapper.getDeptById(users.getDeptId());
                                                hrStaffIncentive.setCreateDeptId(department.getDeptId());
                                            }
                                            hrStaffIncentive.setCreateUserId(cell.getStringCellValue());
                                            break;
                                        case 1:
                                            // 单位员工
                                            if (cell.getStringCellValue() != null) {
                                                Users user = usersMapper.getUserByUserName(cell.getStringCellValue());
                                                hrStaffIncentive.setStaffName(user.getUserId());
                                            }
                                            break;
                                        case 2:
                                            //奖惩项目
                                            hrStaffIncentive.setIncentiveItem(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            // 奖惩日期
//                                            String result = null;
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
//                                                result = sdf.format(date);
                                                hrStaffIncentive.setIncentiveTime(date);
                                                break;
                                            }
                                            hrStaffIncentive.setIncentiveTime(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 4:
                                            // 奖惩月份
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrStaffIncentive.setSalaryMonth(DateFormat.getDatestr(date).substring(0,DateFormat.getDatestr(date).length()-3));
                                                break;
                                                }
                                                hrStaffIncentive.setSalaryMonth(cell.getStringCellValue());
                                                break;
                                        case 5:
                                            // 奖惩属性
                                            hrStaffIncentive.setIncentiveType(cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //金额
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                BigDecimal big1=new BigDecimal(cell.getNumericCellValue());
                                                value = big1.toString();
                                            }
                                            //解决1234.0  去掉后面的.0
                                            if(null!=value&&!"".equals(value.trim())){
                                                String[] item = value.split("[.]");
                                                if(1<item.length&&"0".equals(item[1])){
                                                    value=item[0];
                                                }
                                            }
                                            hrStaffIncentive.setIncentiveAmount(Integer.valueOf(value));
                                            break;
                                        case 7:
                                            // 说明
                                            hrStaffIncentive.setIncentiveDescription(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            // 备注
                                            hrStaffIncentive.setRemark(cell.getStringCellValue());
                                            break;
                                    }

                                }
                            }
                            if(hrStaffIncentive!=null){
                                hrStaffIncentive.setAddTime(new Date());
                                hrStaffIncentive.setLastUpdateTime(new Date());
                                int a =hrStaffIncentiveMapper.insertSelective(hrStaffIncentive);
                                if (a!=0){
                                    success = success + 1;
                                }
                            }

                        }
                    }
                }

            }
            HrStaffIncentiveWithBLOBs temp=new HrStaffIncentiveWithBLOBs();
            temp.setCount(success);
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(temp);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        } finally {
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }

    /**
     * 获取奖惩下拉框的内容（人事代码表）
     * 张丽军
     * @param type
     * @return
     */
    public ToJson<HrCode> getHrCodes(String type) {
        ToJson<HrCode> toJson = new ToJson<>();
        List<HrCode> hrCodes=new ArrayList<>();
        HrCodeExample hrCodeExample=new HrCodeExample();
        HrCodeExample.Criteria criteria = hrCodeExample.createCriteria();
        hrCodeExample.setOrderByClause("cast(CODE_NO as SIGNED INTEGER) ASC");
        if ("item".equals(type)) { //奖惩项目
            criteria.andParentNoEqualTo(HR_ITEM);
            hrCodes = hrCodeMapper.selectByExampleWithBLOBs(hrCodeExample);
        } else if ("value".equals(type)) {//奖惩属性
            criteria.andParentNoEqualTo(HR_VALUE);
            hrCodes=hrCodeMapper.selectByExampleWithBLOBs(hrCodeExample);
        }
        toJson.setMsg("ok");
        toJson.setFlag(0);
        toJson.setObject(hrCodes);
        return  toJson;
    }

    /**
     * 根据条件查询数量
     * @param
     * @param deptId(传入的多个部门的编号)
     * @return 返回的json字符串中  nums是返回的结果的数量
     *
     */
    public ToJson<HrStaffIncentive> selectNumByCon(HrStaffIncentive record,Integer [] deptId){
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId != null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<HrStaffIncentive> list = hrStaffIncentiveMapper.selectNumByCon(map);
            for(HrStaffIncentive hrStaffIncentive : list){
                if(hrStaffIncentive.getIncentiveItem()!=null){
                    if(hrStaffIncentive.getIncentiveItem().equals("1")){
                        hrStaffIncentive.setIncentiveItem1("积极参加工作");
                    }else if(hrStaffIncentive.getIncentiveItem().equals("2")){
                        hrStaffIncentive.setIncentiveItem1("不迟到不早退");
                    }else if(hrStaffIncentive.getIncentiveItem().equals("3")){
                        hrStaffIncentive.setIncentiveItem1("违规操作");
                    }else if(hrStaffIncentive.getIncentiveItem().equals("4")){
                        hrStaffIncentive.setIncentiveItem1("经常迟到早退");
                    }else if(hrStaffIncentive.getIncentiveItem().equals("")){
                        hrStaffIncentive.setIncentiveItem1("");
                    }
                }

                if(hrStaffIncentive.getIncentiveType()!=null){
                    if(hrStaffIncentive.getIncentiveType().equals("REWARD")){
                        hrStaffIncentive.setIncentiveType1("奖励");
                    }else if(hrStaffIncentive.getIncentiveType().equals("PUNISHMENT")){
                        hrStaffIncentive.setIncentiveType1("惩罚");
                    }else if(hrStaffIncentive.getIncentiveType().equals("")){
                        hrStaffIncentive.setIncentiveType1("");
                    }
                }

            }
            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson ;
    }

    public ToJson<HrStaffIncentiveWithBLOBs> getByStaffNameIncentive(String staffName, Integer page, Integer pageSize, boolean useFlag){
        ToJson<HrStaffIncentiveWithBLOBs> json = new ToJson<HrStaffIncentiveWithBLOBs>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<HrStaffIncentiveWithBLOBs> list=hrStaffIncentiveMapper.getByStaffNameIncentive(map);
            if(list.size()>0){
                for(int i=0;i<list.size();i++) {
                    Users user = usersMapper.findUsersByuserId(list.get(i).getStaffName()); //根据 id 找名字
                    list.get(i).setStaffName(user.getUserName());
                    //合同类型
                    HrCode hr_staff_contract2 = hrCodeMapper.selectCode("HR_STAFF_INCENTIVE1",list.get(i).getIncentiveItem());
                    if (hr_staff_contract2 != null) {
                        list.get(i).setIncetiveItemName(hr_staff_contract2.getCodeName());
                    } else {
                        list.get(i).setIncetiveItemName(" ");
                    }
                    if(list.get(i).getIncentiveType().equals("REWARD")){
                        list.get(i).setIncentiveTypeName("奖励");
                    }else if(list.get(i).getIncentiveType().equals("PUNISHMENT")){
                        list.get(i).setIncentiveTypeName("惩罚");

                    }else{
                        list.get(i).setIncentiveTypeName(" ");
                    }
                }
                json.setTotleNum(hrStaffIncentiveMapper.getByStaffNameIncentiveCount(staffName));
                json.setObj(list);
                json.setMsg("true");
            }
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
}
